// 打包 packages 下的模块为 JS 文件
import minimist from "minimist";
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'
import { createRequire } from 'module'
import esbuild from 'esbuild'

// 解析命令行参数
const args = minimist(process.argv.slice(2))
// ESM 下使用 CommonJs 变量
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const require = createRequire(import.meta.url)

// 打包的项目
const target = args._[0] || 'reactivity'
// 打包的格式
const format = args.f || 'iife'

// Node 中 ESM 没有 __dirname
const entry = resolve(__dirname, `../packages/${target}/src/index.ts`)
const pkg = require(`../packages/${target}/package.json`)

esbuild.context({
  entryPoints: [entry],
  outfile: resolve(__dirname, `../packages/${target}/dist/${target}.js`),
  bundle: true, // reactivity => shared => 打包到一起
  platform: "browser",
  sourcemap: true,
  format, // cjs esm iife
  globalName: pkg.buildOptions?.name
}).then((ctx) => {
  console.log('start dev')
  
  return ctx.watch()
})